package com.novoda.runbuddy.provider;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.test.AndroidTestCase;

import com.novoda.runbuddy.R;
import com.novoda.runbuddy.util.DBUtil;

public class RouteSegmentProviderTest extends AndroidTestCase {
	private SQLiteDatabase			mdb;
	private static final String		RUN_BUDDY_DB		= "runBuddyDB1.db";
	private DBUtil					dbUtil				= null;
	private static final Uri		INSERT_NEW_SEGMENT	= Uri.parse("content://com.novoda.runbuddy/routes/1/segments");

	private static final Uri		ALL_SEG_4_ROUTE		= Uri.parse("content://com.novoda.runbuddy/routes/1/segments");
	private static final Uri		SECOND_SEG_4_ROUTE	= Uri.parse("content://com.novoda.runbuddy/routes/1/segments/2");

	private static final String[]	ALL_COL				= new String[] {
			RunBuddyCP.RouteSegments.CHECKPOINT,
			RunBuddyCP.RouteSegments.DISTANCE			};

	protected void setUp() {
		if (dbUtil == null) {
			dbUtil = new DBUtil(getContext(), RUN_BUDDY_DB);
		}
		// insert initial values
		dbUtil.executeDB(R.raw.positron_cp_route_insert);
		mdb = dbUtil.getDatabase();
	}

	@Override
	protected void tearDown() throws Exception {
		if (dbUtil == null) {
			dbUtil = new DBUtil(getContext(), RUN_BUDDY_DB);
		}
		dbUtil.executeDB(R.raw.db_delete_all_values);
		mdb.close();
		super.tearDown();
	}

	public void testQueryingAllSegmentsForRoute() throws Exception {
		Cursor cur = getContext().getContentResolver().query(ALL_SEG_4_ROUTE, new String[] { RunBuddyCP.RouteSegments.DISTANCE },
				null, null, null);
		assertNotNull(cur);
		assertEquals(4, cur.getCount());
		double actual[] = new double[] { 0, 100, 200, 110 };
		while (cur.moveToNext()) {
			assertEquals(actual[cur.getPosition()], cur.getDouble(0));
		}
	}

	public void testGettingAllColumnsForSingleRouteSegment() throws Exception {
		Cursor cur = getContext().getContentResolver().query(SECOND_SEG_4_ROUTE, ALL_COL, null, null, null);
		assertNotNull(cur);
		String checkpoint = "content://com.novoda.runbuddy/checkpoints/3";
		double distance = 200;
		cur.moveToFirst();
		assertEquals(checkpoint, cur.getString(0));
		assertEquals(distance, cur.getDouble(1));
	}

	public void testInsertNewSegment() throws Exception {
		ContentValues values = new ContentValues();
		values.put(RunBuddyCP.RouteSegments.CHECKPOINT, "content://com.novoda.runbuddy/checkpoints/3");
		Uri uri = getContext().getContentResolver().insert(INSERT_NEW_SEGMENT, values);
		Uri expected = Uri.parse("content://com.novoda.runbuddy/routes/1/segments/4");
		assertEquals(expected, uri);
	}
}
